<template>
    <div class="app-container">
        <el-row :gutter="24">
            <!-- 表格 -->
            <el-col :span="24" :xs="24">
                <!--表格搜索栏-->
                <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
                    <el-form-item label="设备名称" prop="deviceName">
                        <el-select v-model="queryParams.deviceName" filterable clearable placeholder="请选择设备名称">
                            <el-option v-for="dict in equipmentOptions" :key="dict.equipmentCode"
                                :label="dict.equipmentName" :value="dict.equipmentCode"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备厂家" prop="equipmentManufacturer">
                        <el-input v-model="queryParams.equipmentManufacturer" placeholder="请输入手机号码" clearable
                            size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="已维护日期" prop="maintainDate">
                        <el-input v-model="queryParams.maintainDate" placeholder="请输入已维护日期" clearable size="small"
                            style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="计划维护日期" prop="plannedMaintenanceDate">
                        <el-date-picker v-model="queryParams.plannedMaintenanceDate" type="date" placeholder="选择维护日期"
                            value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                            v-hasPermi="['shebei:weihu:add']">新增</el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
                <!-- 表格数据 -->
                <el-table v-loading="loading" :data="shebeiWhList">
                    <!-- <el-table-column type="selection" width="50" align="center" /> -->
                    <el-table-column prop="id" label="序号" width="50" type="index" align="center"
                        :index="(index) => index + 1" />
                    <el-table-column label="设备名称" align="center" prop="deviceName" />
                    <el-table-column label="设备厂家" align="center" prop="equipmentManufacturer"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="购买日期" align="center" prop="buyDate" :show-overflow-tooltip="true" />
                    <el-table-column label="PM级别" align="center" prop="pmLevel" :show-overflow-tooltip="true" />
                    <el-table-column label="已维护日期" align="center" prop="maintenanceIntervals"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="维护周期/天" align="center" prop="maintenanceIntervals"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="计划维护日期" align="center" prop="plannedMaintenanceDate"
                        :show-overflow-tooltip="true">

                    </el-table-column>
                    <el-table-column label="备注" align="center" prop="remark" width="150" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <span>{{whRender(scope.row)}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width"
                        fixed="right">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                v-hasPermi="['shebei:weihu:edit']">修改</el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                                v-hasPermi="['shebei:weihu:remove']">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
            </el-col>
        </el-row>

        <!-- 添加或修改设备维护对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="closeDialog">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="设备厂家" prop="equipmentManufacturer">
                            <el-input v-model="form.equipmentManufacturer" placeholder="请输入设备编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="设备名称" prop="deviceName">
                            <el-select v-model="form.deviceName" filterable placeholder="请选择设备名称" :disabled="editOpen">
                                <el-option v-for="dict in equipmentOptions" :key="dict.equipmentCode"
                                    :label="dict.equipmentName" :value="dict.equipmentCode"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="购买日期" prop="buyDate">
                            <el-date-picker v-model="form.buyDate" type="date" placeholder="选择购买日期"
                                value-format="yyyy-MM-dd HH:mm:ss"> </el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="PM级别" prop="pmLevel">
                            <el-input v-model="form.pmLevel" placeholder="请输入PM级别" maxlength="11" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="已维护日期" prop="maintainDate">
                            <el-date-picker v-model="form.maintainDate" type="date" placeholder="选择已维护日期"
                                value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="计划维护日期" prop="plannedMaintenanceDate">
                            <el-date-picker v-model="form.plannedMaintenanceDate" type="date" placeholder="选择计划维护日期"
                                value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row>
                    <el-col :span="12">
                        <el-form-item :span="12" label="维护周期/天" prop="maintenanceIntervals">
                            <el-input v-model="form.maintenanceIntervals" placeholder="请输入维护周期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" placeholder="请输入维护周期" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 设备信息对话框 -->
        <el-dialog title="维护提醒" :visible.sync="shebeiInfo.visible" width="1000px" append-to-body @close="closeWhDialog">
            <el-table v-loading="loading" :data="sbwhList">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column prop="id" label="序号" width="50" type="index" align="center"
                    :index="(index) => index + 1" />
                <el-table-column label="设备名称" align="center" prop="deviceName" />
                <el-table-column label="设备厂家" align="center" prop="equipmentManufacturer"
                    :show-overflow-tooltip="true" />
                <el-table-column label="购买日期" align="center" prop="buyDate" :show-overflow-tooltip="true" />
                <el-table-column label="PM级别" align="center" prop="pmLevel" :show-overflow-tooltip="true" />
                <el-table-column label="已维护日期" align="center" prop="maintenanceIntervals"
                    :show-overflow-tooltip="true" />
                <el-table-column label="维护周期/天" align="center" prop="maintenanceIntervals"
                    :show-overflow-tooltip="true" />
                <el-table-column label="计划维护日期" align="center" prop="plannedMaintenanceDate"
                    :show-overflow-tooltip="true" />
                <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true">
                    <!-- <template slot-scope="scope">
                        <el-switch v-if="dateArrived(scope.row)" v-model="scope.row.bz" active-value="0"
                            inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
                    </template> -->
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileFormWh">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip">
                    <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                    <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
                </div>
                <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        listUser,
        getUser,
        delUser,
        addUser,
        updateUser,
        exportUser,
        resetUserPwd,
        changeUserStatus,
        importTemplate,
    } from "@/api/system/user";
    import { getSbwhList, detailSbwhList, addSbwh, updateSbwh, delSbwh } from "@/api/shebei";
    import { getToken } from "@/utils/auth";
    import { treeselect } from "@/api/system/dept";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    import { addSb, getSbList, updateSb, delSb, exportSb, treeselectSb, } from "@/api/shebei";

    export default {
        name: "Weihu",
        components: { Treeselect },
        data() {
            return {
                //设备信息弹窗
                shebeiInfo: {
                    visible: false,
                    title: '',
                },
                editOpen: false,
                equipmentOptions: [],
                sbwhList: [],
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 表格数据
                shebeiWhList: null,
                // 弹出层标题
                title: "",
                // 部门树选项
                deptOptions: undefined,
                // 是否显示弹出层
                open: false,
                // 部门名称
                deptName: undefined,
                // 默认密码
                initPassword: undefined,
                // 日期范围
                dateRange: [],
                // 状态数据字典
                statusOptions: [],
                // 性别状态字典
                sexOptions: [],
                // 岗位选项
                postOptions: [],
                // 角色选项
                roleOptions: [],
                // 表单参数
                form: {},
                defaultProps: {
                    children: "children",
                    label: "label",
                },
                // 用户导入参数
                upload: {
                    // 是否显示弹出层（用户导入）
                    open: false,
                    // 弹出层标题（用户导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 是否更新已经存在的用户数据
                    updateSupport: 0,
                    // 设置上传的请求头部
                    headers: { Authorization: "Bearer " + getToken() },
                    // 上传的地址
                    url: process.env.VUE_APP_BASE_API + "/system/user/importData",
                },
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,

                },
                // 表单校验
                rules: {
                    userName: [
                        { required: true, message: "用户名称不能为空", trigger: "blur" },
                    ],
                    nickName: [
                        { required: true, message: "用户昵称不能为空", trigger: "blur" },
                    ],
                },
            };
        },
        watch: {
            // 根据名称筛选部门树
            deptName(val) {
                this.$refs.tree.filter(val);
            },
        },
        created() {
            this.getList();
            this.getTreeselect();
            this.getSbList()
            this.whRender()
            this.getDicts("sys_normal_disable").then((response) => {
                this.statusOptions = response.data;
            });
            this.getDicts("sys_user_sex").then((response) => {
                this.sexOptions = response.data;
            });
            this.getConfigKey("sys.user.initPassword").then((response) => {
                this.initPassword = response.msg;
            });
        },
        methods: {
            //提醒设备维护
            whRender(row) {
                var now = new Date();
                var year = now.getFullYear(); //得到年份
                var month = now.getMonth(); //得到月份
                var date = now.getDate(); //得到日期
                month = month + 1;
                if (month < 10) month = "0" + month;
                if (date < 10) date = "0" + date;
                var time = year + "-" + month + "-" + date + ' 00:00:00'; //（格式化"yyyy-MM-dd"）
                const res = localStorage.getItem('visible')
                console.log('res', res);
                if (res === false) {
                    return
                }
                // if (row?.plannedMaintenanceDate === time) {
                //     localStorage.setItem('visible', true)
                //     return this.shebeiInfo.visible = res
                // }
            },
            /** 查询设备列表 */
            getSbList() {
                this.loading = true;
                //console.log(this.addDateRange(this.queryParams, this.dateRange));
                getSbList(this.queryParams).then(
                    (response) => {
                        // console.log(response)
                        this.equipmentOptions = response.rows;

                    }
                );
            },
            //已到维护日期
            submitFileFormWh() {
                this.shebeiInfo.visible = false
            },
            /** 查询用户列表 */
            getList() {
                this.loading = true;
                //console.log(this.addDateRange(this.queryParams, this.dateRange));
                getSbwhList(this.queryParams).then(
                    (response) => {
                        // console.log(response)
                        this.shebeiWhList = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    }
                );
            },
            /** 查询部门下拉树结构 */
            getTreeselect() {
                treeselect().then((response) => {
                    this.deptOptions = response.data;
                });
            },
            // 筛选节点
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            // 节点单击事件
            handleNodeClick(data) {
                this.queryParams.deptId = data.id;
                this.getList();
            },

            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
                this.getList()
                this.shebeiInfo.visible = false
                localStorage.setItem('visible', false)
                const res = localStorage.getItem('visible')

            },
            closeDialog() {
                this.getList()
            },
            closeWhDialog() {
                this.shebeiInfo.visible = false
                localStorage.setItem('visible', false)
            },
            // 表单重置
            reset() {
                this.form = {};
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.page = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.resetForm("queryForm");
                this.handleQuery();
            },

            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加维修设备";
                this.editOpen = false

            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                this.open = true;
                this.title = "修改维修设备";
                this.form = row
                this.editOpen = true
            },

            /** 提交按钮 */
            submitForm: function () {
                this.$refs["form"].validate((valid) => {
                    if (valid) {
                        if (this.title === '修改维修设备') {
                            updateSbwh(this.form).then((response) => {
                                if (response.code === 200) {
                                    this.msgSuccess("修改成功");
                                    this.open = false;
                                    this.getList();
                                }
                            });
                        } else {
                            addSbwh(this.form).then((response) => {
                                if (response.code === 200) {
                                    this.msgSuccess("新增成功");
                                    this.open = false;
                                    this.getList();
                                }
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const userIds = row.userId || this.ids;
                this.$confirm(
                    '是否确认删除维修设备名称为"' + row.deviceName + '"的数据项?',
                    "警告",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(function () {
                        return delSbwh(row.id);
                    })
                    .then(() => {
                        this.getList();
                        this.msgSuccess("删除成功");
                    })
                    .catch(function () { });
            },
            /** 导出按钮操作 */
            handleExport() {
                const queryParams = this.queryParams;
                this.$confirm("是否确认导出所有用户数据项?", "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(function () {
                        return exportUser(queryParams);
                    })
                    .then((response) => {
                        this.download(response.msg);
                    })
                    .catch(function () { });
            },
            /** 导入按钮操作 */
            handleImport() {
                this.upload.title = "用户导入";
                this.upload.open = true;
            },
            /** 下载模板操作 */
            importTemplate() {
                importTemplate().then((response) => {
                    this.download(response.msg);
                });
            },
            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
                this.getList();
            },
            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();
            },
        },
    };
</script>